package mo.offer_version2;

import mo.common.TreeNode;

import java.util.*;

@SuppressWarnings("DuplicatedCode")
public class L32_3 {

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        boolean right = false;
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> row = new ArrayList<>();
            while (size > 0) {
                TreeNode node = queue.poll();
                row.add(node.val);
                if (node.left != null) {
                    queue.add(node.left);
                }
                if (node.right != null) {
                    queue.add(node.right);
                }
                size--;
            }
            if (right) {
                Collections.reverse(row);
            }
            res.add(row);
            right = !right;
        }
        return res;
    }

}
